﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Library
{
    public class MyAjaxValidator : BaseValidator, ICallbackEventHandler
    {
        public event ServerValidateEventHandler ServerValidate;

        string _controlToValidateValue;

        protected override bool EvaluateIsValid()
        {
            string controlToValidateValue = this.GetControlValidationValue(this.ControlToValidate);
            return ExecuteValidationFunction(controlToValidateValue);
        }

        protected override void OnPreRender(EventArgs e)
        {
            String eventRef = Page.ClientScript.GetCallbackEventReference(this, "", "", "");
            String includeScript = Page.ResolveClientUrl("~/js/MyAjaxValidator.js");
            Page.ClientScript.RegisterClientScriptInclude("MyAjaxValidator", includeScript);
            String startupScript = String.Format("document.getElementById('{0}').evaluationfunction = 'MyAjaxValidatorEvaluateIsValid';", this.ClientID);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "MyAjaxValidator", startupScript, true);
            base.OnPreRender(e);
        }

        protected override bool DetermineRenderUplevel()
        {
            return Context.Request.Browser.SupportsCallback;
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            _controlToValidateValue = eventArgument;
        }

        public string GetCallbackResult()
        {
            return ExecuteValidationFunction(_controlToValidateValue).ToString();
        }

        private bool ExecuteValidationFunction(String controlToValidateValue)
        {
            ServerValidateEventArgs args = new ServerValidateEventArgs(controlToValidateValue, this.IsValid);

            if (ServerValidate != null)
                ServerValidate(this, args);

            return args.IsValid;
        }

        #region ICallbackEventHandler Members

        string ICallbackEventHandler.GetCallbackResult()
        {
            throw new NotImplementedException();
        }

        void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
